package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.wcs.exam.common.base.page.Page;
import com.wcs.exam.common.base.page.PageUtil;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.dao.po.ExamUserRankPO;
import com.wcs.exam.dao.ExamUserDao;
import com.wcs.exam.dao.impl.mapper.entity.ExamUser;
import com.wcs.exam.dao.impl.mapper.ExamUserMapper;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * 考试用户 持久化实现类
 *
 * @author wcs
 * @since 2025-03-13
 */
@RequiredArgsConstructor
@Repository
public class ExamUserDaoImpl extends ServiceImpl<ExamUserMapper, ExamUser> implements ExamUserDao {

    @NotNull
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public <R> List<R> selectObjs(Wrapper<ExamUser> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public Integer getMaxSort() {
        return lambdaQuery().orderByDesc(ExamUser::getSort).last(SqlUtil.limitOne()).oneOpt().map(ExamUser::getSort).orElse(0);
    }

    @Override
    public ExamUser getByExamIdAndUserId(Long examId, Long userId) {
        return lambdaQuery()
                .eq(ExamUser::getExamId, examId)
                .eq(ExamUser::getUserId, userId)
                .last(SqlUtil.limitOne())
                .one();
    }

    @Override
    public ExamUser getByExamTypeAndExamIdAndUserId(Integer examType, Long examId, Long userId) {
        return lambdaQuery()
                .eq(ExamUser::getExamType, examType)
                .eq(ExamUser::getExamId, examId)
                .eq(ExamUser::getUserId, userId)
                .last(SqlUtil.limitOne())
                .one();
    }

    @Override
    public Integer getRankNoByExamTypeAndExamIdAndUserId(Integer examType, Long examId, Long userId) {
        String sql = "select * from (select user_id, user_score, RANK() OVER (ORDER BY user_score DESC) AS rankNo from exam_user where exam_type = :examType and exam_id = :examId) as rs where user_id = :userId limit 1";

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("examType", examType);
        paramMap.put("examId", examId);
        paramMap.put("userId", userId);
        Map<String, Object> resultMap = namedParameterJdbcTemplate.queryForMap(sql, paramMap);

        if (CollectionUtil.isEmpty(resultMap)) {
            return null;
        }
        if (resultMap.containsKey("rankNo")) {
            return Integer.valueOf(resultMap.get("rankNo").toString());
        }
        return null;
    }

    @Override
    public Page<ExamUserRankPO> rankPage(Integer examType, Long examId, Collection<Long> userIds, long pageCurrent, long pageSize) {
        String sql = "select * from ( select" +
                " user_id as userId, exam_id as examId, exam_type as examType, user_score as userScore," +
                " exam_submit_time as examSubmitTime, user_answer_time as userAnswerTime," +
                " user_exam_status as userExamStatus, user_evaluation_status as userEvaluationStatus," +
                " RANK() OVER (ORDER BY user_score DESC) AS rankNo" +
                " from exam_user where exam_type = :examType and exam_id = :examId" +
                ") as rt";

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("examType", examType);
        paramMap.put("examId", examId);
        if (CollectionUtil.isNotEmpty(userIds)) {
            paramMap.put("userIds", userIds);
            sql += " and user_id in (:userIds)";
        }

        // 统计
        String countSql = sql.replace("select *", "select count(*)");

        // 统计总数
        Long count = namedParameterJdbcTemplate.queryForObject(countSql, paramMap, Long.class);
        long totalCount = ObjectUtil.isNotNull(count) ? count : 0L;

        pageCurrent = PageUtil.checkCurrent(totalCount, pageSize, pageCurrent);
        pageSize = PageUtil.checkSize(pageSize);
        long totalPage = PageUtil.countTotalSize(totalCount, pageSize);

        String pageSql = sql + PageUtil.limitSql(totalCount, pageCurrent, pageSize);
        List<ExamUserRankPO> rankList = namedParameterJdbcTemplate.query(pageSql, paramMap, BeanPropertyRowMapper.newInstance(ExamUserRankPO.class));

        return new Page<>(rankList, (int) totalCount, (int) totalPage, (int) pageCurrent, (int) pageSize);
    }
}
